import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //这个方法用于获取博客列表页 以及 每篇博客详情
        ObjectMapper objectMapper = new ObjectMapper();
        String blogId = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        resp.setContentType("application/json;charset=utf8");
        //判断当前是哪个界面 blogId = null 是博客列表页 不为空是博客详情页
        if(blogId == null) {
            List<Blog> blogList = new ArrayList<>();
            //返回blog数据库中所有博客
            blogList = blogDao.selectAll();
            resp.getWriter().write(objectMapper.writeValueAsString(blogList));
        } else {
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            //返回blogId对应博客
            resp.getWriter().write(objectMapper.writeValueAsString(blog));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1. 先检查一下用户的登陆状态, 获取到会话和用户信息.
        //    如果未登录, 显然不能提交博客~
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录, 不能发布博客!");
            return;
        }

        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录, 不能发布博客!");
            return;
        }

        // 2. 获取请求中的参数(博客的标题和正文)
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");

        //3.构造blog对象 并将博客添加到数据库中
        BlogDao blogDao = new BlogDao();
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        blogDao.insert(blog);
        resp.sendRedirect("blog_list.html");

    }
}
